// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Jeff Stewart
//
// Extracts information from the localhost for the report.

#include <QtNetwork/QHostInfo>
#include <QtCore/QDate>
#include <QtCore/QTime>

#include "probes/localhost.h"

namespace popdiag {

// leaving FormatOffsetInMinutes at the top to make the diff simple
// TODO: Move it below the ctor to take an offset in minutes and turn it
// into ISO-style "-0500" type string description.
// Offset to be applied to GMT to get local time.
QString LocalHostProbe::FormatOffsetInMinutes(int minutes) {
  if (minutes == INT_MAX) {
    return "????";
  }
  bool neg = minutes < 0;
  if (neg) {
    minutes = -minutes;
  }
  int hours = minutes / 60;
  int min_left = minutes % 60;
  QString rval;
  // the Qt way to do sprintf:
  return QString("%1%2%3").arg(neg ? "-" : "")
                          .arg(hours, 2, 10, QChar('0'))
                          .arg(min_left, 2, 10, QChar('0'));
}

LocalHostProbe::LocalHostProbe()
  : Probe("Localhost"), executed_(false) {
}

void LocalHostProbe::StartProbe() {
  StartLogDetails();
  LogTime();
  LogTimeZone();
  LogLocale();
  LogOSVersion();
  EndLogDetails();
  executed_ = true;
  emit ProbeComplete(PROBE_OK);
}

void LocalHostProbe::LogTime() {
  QDate today = QDate::currentDate();
  QTime now = QTime::currentTime();
  LogDetails("Date/Time", true,
             today.toString(Qt::ISODate) + " " + now.toString(Qt::ISODate));
}

void LocalHostProbe::LogTimeZone() {
  int offset_in_minutes = GetOffsetFromGMTInMinutes();
  QString tzdesc = FormatOffsetInMinutes(offset_in_minutes);
  QString tzname = GetTimezoneName();
  LogDetails("Timezone", true, tzname);
  LogDetails("UTC Offset", true, tzdesc);
}

}  // namespace popdiag
